package org.st.js4nk;

import cn.nukkit.Server;
import cn.nukkit.command.CommandSender;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;

public class JSRunner implements Runnable {
    File jsfile = null;
    CommandSender commandSender;
    String[] args;
    public JSRunner(File jsfile) {
        this.jsfile = jsfile;
    }

    public void setCommandSender(CommandSender commandSender) {
        this.commandSender = commandSender;
    }

    public void setArgs(String[] args) {
        this.args = args;
    }

    @Override
    public void run() {

        this.runjs("main", commandSender,args);
    }

    public void runjs(String method, Object... args) {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        Invocable invocable = (Invocable) nashorn;

        try {
            nashorn.eval(new BufferedReader(new InputStreamReader(new FileInputStream(jsfile), "UTF-8")));  //为了解决编码问题
            invocable.invokeFunction(method, args);
        } catch (ScriptException e) {
            Server.getInstance().getLogger().error(e.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }


}